package cn.element.io.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * 基于NIO实现客户端
 */
public class Client {

    public static void main(String[] args) throws IOException {
        // 1.获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8848));
        
        // 2.切换成非阻塞模式
        socketChannel.configureBlocking(false);
        
        // 3.分配缓冲区大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        
        // 4.发送数据给服务端
        Scanner sc = new Scanner(System.in);
        
        while (true) {
            System.out.println("请说: ");
            String line = sc.nextLine();
            
            buffer.put(("洛必达: " + line).getBytes());
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
    }

}
